<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="roleList" stripe border>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom',i1 ===0 ? 'bdtop':'','vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 渲染二级权限 -->
                <el-row
                  :class="[i2 === 0? '':'bdtop','vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              @click="showEditDialog(scope.row.id)"
              icon="el-icon-edit"
              size="mini"
            >编辑</el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            >删除</el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightDialog(scope.row)"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog title="添加用户" @close="rolesDialogClosed" :visible.sync="addDialogVisible" width="50%">
      <el-form
        :model="addForm"
        :rules="RolesName"
        ref="rolesFormRef"
        label-width="90px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色 -->
    <el-dialog
      title="添加用户"
      @close="editDialogClosed"
      :visible.sync="rolesDialogVisible"
      width="50%"
    >
      <el-form
        :model="editForm"
        :rules="RolesName"
        ref="rolesFormRef"
        label-width="90px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" @close ="setRightDialogClosed" :visible.sync="setRightDialogVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        ref="treeRef"
        default-expand-all
        :default-checked-keys="defKeys"
      ></el-tree>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesDialogVisible: false,
      addDialogVisible: false,
      //分配权限
      setRightDialogVisible: false,
      //获取所选择修改的角色的值
      editForm: {},
      //验证输入的值
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      RolesName: {
        roleName: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
        ],
      },
      //角色列表数据
      roleList: [],
      //权限数据
      rightslist: [],
      //树形控件的绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      //选中默认的节点Id值
      defKeys: [],
      //当前即将分配权限的角色ID
      roleId: ''
    };
  },

  created() {
    this.getRolesList();
  },

  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");

      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.roleList = res.data;

      console.log(this.roleList);
    },
    async addRoles() {
      const { data: res } = await this.$http.post("roles", this.addForm);
      if (res.meta.status !== 201) {
        return this.$message.error("添加失败");
      }
      this.$message.success("添加成功");
      this.addDialogVisible = false;
      this.getRolesList();
    },
    rolesDialogClosed() {
      this.$refs.rolesFormRef.resetFields();
    },
    editDialogClosed() {
      this.$refs.rolesFormRef.resetFields();
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("无法编辑用户");
      }

      this.editForm = res.data;
      this.rolesDialogVisible = true;
    },
    editRoles() {
      this.$refs.rolesFormRef.validate(async (valid) => {
        if (!valid) return;

        //解构赋值
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        );

        if (res.meta.status !== 200) {
          this.$message.error("修改角色失败");
        }
        this.$message.success("修改角色成功！");
        //隐藏用户对话框
        this.rolesDialogVisible = false;
        //重新获取用户列表
        this.getRolesList();
      });
    },
    async removeUserById(id) {
      const confirmResult = await this.$confirm("是否删除该角色?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err); //处理报错

      //点击确定confirmResult打印出confirm
      //点击取消confirmResult打印出cancel
      if (confirmResult !== "confirm") {
        return this.$message.info("取消删除");
      }
      //删除用户
      const { data: res } = await this.$http.delete("roles/" + id);

      if (res.meta.status !== 200) {
        this.$message.success("删除失败");
      }
      this.$message.success("角色删除成功");
      this.getRolesList();
    },
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm("是否删除该权限?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch((err) => err); //处理报错

      if (confirmResult !== "confirm") {
        return this.$message.info("取消删除");
      }
      //删除权限
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );

      if (res.meta.status !== 200) {
        this.$message.success("删除失败");
      }
      this.$message.success("删除权限成功");
      role.children = res.data;
    },
    //展示分配权限的数据
    async showSetRightDialog(role) {
      const { data: res } = await this.$http.get("rights/tree");
      this.roleId = role.id
      if (res.meta.status !== 200) {
        return this.$message.error("获取数据失败");
      }
      //把获取到的权限数据给rightslist
      this.rightslist = res.data;
      //递归获取三级权限
      this.getLeafKeys(role, this.defKeys);

      this.setRightDialogVisible = true;
      //console.log(this.defKeys)
    },
    //通过递归形式，角色下的三级权限id 并保存在defKeys数组中
    getLeafKeys(node, arr) {
      //如果当前 node 节点不包括children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    //监听分配权限的对话框
    setRightDialogClosed() {
      this.defKeys = []
    },
    //分配权限提交
   async allotRoles(){
      const keys = [
        this.$refs.treeRef.getCheckedKeys(),
        this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const idStr = keys.join(',')

     const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
    
     if(res.meta.status !==200) {
       return this.$message.error('分配权限失败')
     }

     this.$message.success('分配权限成功')
     this.getRolesList()

     this.setRightDialogVisible = false
    }
    
  },
};
</script>
<style lang='css' scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>